﻿// Author:  Marco van Wieren <mailto:mvwieren@gmail.com>
// Year:    2012
// License: Microsoft Public License (Ms-PL)

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace Mvw.SharePoint.Taxonomy.AutoTagging
{
	/// <summary>
	/// Web Events
	/// </summary>
	public class WorkspaceWebEvents : SPWebEventReceiver
	{
        /// <summary>
        /// A site was provisioned.
        /// </summary>
        public override void WebProvisioned(SPWebEventProperties properties)
        {
            using (var currWeb = properties.Web)
            {
                // Ensure that we're not interfering too much with site collections that are "unmanaged"
                // TODO Not sure what this code should do
                var parentWeb = currWeb.ParentOrRootWeb();
                if (parentWeb.AllProperties["WorkspaceTermInfo"] == null)
                {
                    if (!currWeb.Equals(parentWeb))
                    {
                        parentWeb.Dispose();
                    }
                    return;
                }

                currWeb.EnsureRequiredFeatures(false, true, false);

                // Initially a new sub site is set to inherit metadata
                currWeb.AllProperties["WorkspaceTermInfoInherit"] = true.ToString();

                // Now ensure the taxonomy columns are created and the WorkspaceTermInfo object is saved with the web object
                currWeb.InheritWorkspaceTermInfo(false);
            }
            base.WebProvisioned(properties);
        }
	}
}
